import React, { useState, useEffect } from 'react';

function LifecycleDemo() {
  const [count, setCount] = useState(0);
  const [message, setMessage] = useState('组件已创建');
  
  // 模拟 componentDidMount
  useEffect(() => {
    console.log('组件已挂载');
    setMessage('组件已挂载');
    
    const logElement = document.getElementById('lifecycle-log');
    if (logElement) {
      logElement.innerHTML += '<p class="mount">子组件已挂载 (Mount)</p>';
    }
    
    // 返回清理函数，模拟 componentWillUnmount
    return () => {
      console.log('子组件将卸载');
      
      // 安全地检查元素是否存在
      const logElement = document.getElementById('lifecycle-log');
      if (logElement) {
        logElement.innerHTML += '<p class="unmount">子组件已卸载 (Unmount)</p>';
      }
    };
  }, []);
  
  // 模拟 componentDidUpdate
  useEffect(() => {
    if (count > 0) {
      console.log(`计数已更新为 ${count}`);
      
      const logElement = document.getElementById('lifecycle-log');
      if (logElement) {
        logElement.innerHTML += `<p class="update">状态已更新: 计数 = ${count} (Update)</p>`;
      }
    }
  }, [count]);
  
  const handleIncrement = () => {
    setCount(count + 1);
  };
  
  console.log('渲染方法执行');
  
  return (
    <div className="lifecycle-demo">
      <h3>React 生命周期演示</h3>
      <p>状态: {message}</p>
      <p>计数: {count}</p>
      <button onClick={handleIncrement}>增加</button>
    </div>
  );
}

export default LifecycleDemo;